package com.example.study.source

import androidx.paging.PagingSource
import androidx.paging.PagingState

/**
 * Created by lijinxi on 2024/2/28
 * @Description:
 */
class CustomPagingSource(private val resp: MovieRepository) : PagingSource<Int, Movie>() {
    override fun getRefreshKey(state: PagingState<Int, Movie>): Int? {
        return state.anchorPosition?.plus(MovieRepository.PER_PAGE)
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> {
        try {
            val since = params.key ?: 0
            val movies = resp.getMovies(since)
            if (movies != null) {
                val prev = (since - MovieRepository.PER_PAGE).let {
                    if (it > 0) it
                    else null
                }
                val next = since + MovieRepository.PER_PAGE
                return LoadResult.Page(movies, prev, next)
            }
        } catch (e: Exception) {
            return LoadResult.Error(e)
        }
        return LoadResult.Invalid()
    }
}